package com.neusoft.elmboot.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.neusoft.elmboot.po.Comment;
import com.neusoft.elmboot.service.BusinessService;
import com.neusoft.elmboot.service.CommentService;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.service.PointsService;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.util.PointUtils;
import com.neusoft.elmboot.util.response.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@RestController
@RequestMapping("/elm/CommentController")
public class CommentController {

    @Autowired
    CommentService commentService;

    @Autowired
    UserService userService;

    @Autowired
    BusinessService businessService;

    @Autowired
    PointsService pointsService;

    @RequestMapping("/user/createComment")
    public ResultBody createComment(Comment comment) throws Exception {
        try {
            String userId = comment.getUserId();
            String businessId = comment.getBusinessId();
            if (userId == null || businessId == null) {
                return ResultBody.error("无效的评论", null);
            }

            if (userService.getUserById(userId) == 0) {
                return ResultBody.error("用户不存在", null);
            }

            if (businessService.getBusinessById(businessId) == null) {
                return ResultBody.error("商家不存在", null);
            }

            String remark = comment.getRemark();
            if (remark != null) {
                remark = remark.trim();
            }
            if (remark == null || remark.isEmpty()) {
                return ResultBody.error("评论不能为空", null);
            }

            Integer starRating = comment.getStarRating();
            if (starRating == null || starRating < 1 || starRating > 5) {
                return ResultBody.error("评分必须在1到5之间", null);
            }

            commentService.createComment(comment);
            pointsService.addPointsFromComment(userId, PointUtils.COMMENT_POINT);
            return ResultBody.success("评论成功", null);
        } catch (Exception e) {
            return ResultBody.error("评论失败", null);
        }
    }

    @RequestMapping("/getBusinessRating")
    public ResultBody getBusinessRating(@RequestParam String businessId) throws Exception {
        try {
            if (businessService.getBusinessById(businessId) == null) {
                return ResultBody.error("不存在该商家", null);
            }
            Double avgRating = commentService.getAverageRatingByBusinessId(businessId);
            List<Comment> commentList = commentService.showComments(businessId);
            JSONObject result = new JSONObject();
            result.putOpt("avgRating", avgRating != null ? avgRating : 0.0);
            result.putOpt("totalComments", commentList != null ? commentList.size() : 0);
            return ResultBody.success("获取评分成功", result);
        } catch (Exception e) {
            return ResultBody.error("获取评分失败", null);
        }
    }

    @RequestMapping("/user/delComment")
    public ResultBody delCommentUser(@RequestParam String userId,
                                     @RequestParam List<Integer> commentIdList) throws Exception{
        try {
            int userCount = userService.getUserById(userId);
            if (userCount == 0) {
                return ResultBody.error("不存在该用户", null);
            }

            List<Integer> userCommentList = commentService.getCommentIdByUserId(userId);
            if (!new HashSet<>(userCommentList).containsAll(commentIdList)){
                return ResultBody.error("你不能删除别人的评论", null);
            }

            commentService.delCommentUser(commentIdList);
            return ResultBody.success("删除成功！",null);

        } catch (Exception e) {
            return ResultBody.error("删除失败", null);
        }
    }

    @RequestMapping("/showComments")
    public ResultBody showComments(@RequestParam String businessId) throws Exception{
        try {
            if (businessService.getBusinessById(businessId) == null) {
                return ResultBody.error("不存在该商家", null);
            }
            JSONArray re = new JSONArray();
            List<Comment> commentList = commentService.showComments(businessId);
            if (!commentList.isEmpty()) {
                for (Comment comment : commentList) {
                    JSONObject object = new JSONObject();

                    String userId = comment.getUserId();
                    User user = userService.getUserInfoById(userId);
                    String userName = (user != null && user.getUserName() != null) ? user.getUserName() : "匿名用户";
                    object.putOpt("username", userName);
                    object.putOpt("remark", comment.getRemark());
                    object.putOpt("starRating", comment.getStarRating());

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    LocalDateTime updateTime = comment.getUpdateTime();
                    if (updateTime != null) {
                        Date date = Date.from(updateTime.atZone(ZoneId.systemDefault()).toInstant());
                        object.putOpt("commentTime", sdf.format(date));
                    } else {
                        object.putOpt("commentTime", "");
                    }

                    re.add(object);
                }
            }
            return ResultBody.success("展示成功！", re);
        } catch (Exception e) {
            return ResultBody.error("获取评论失败", null);
        }
    }

    /**
     * 商家端查看自己店铺的评论列表（匿名用户ID）
     */
    @RequestMapping("/business/showComments")
    public ResultBody showCommentsForBusiness(@RequestParam String businessId) throws Exception {
        try {
            if (businessService.getBusinessById(businessId) == null) {
                return ResultBody.error("不存在该商家", null);
            }
            JSONArray re = new JSONArray();
            List<Comment> commentList = commentService.showComments(businessId);
            if (!commentList.isEmpty()) {
                for (Comment comment : commentList) {
                    JSONObject object = new JSONObject();
                    String userId = comment.getUserId();
                    // 匿名化用户ID，例如只保留后4位
                    String maskedId;
                    if (userId == null || userId.isEmpty()) {
                        maskedId = "匿名用户";
                    } else if (userId.length() <= 4) {
                        maskedId = "用户***" + userId;
                    } else {
                        maskedId = "用户***" + userId.substring(userId.length() - 4);
                    }
                    object.putOpt("reviewerId", maskedId);
                    object.putOpt("remark", comment.getRemark());
                    object.putOpt("starRating", comment.getStarRating());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    LocalDateTime updateTime = comment.getUpdateTime();
                    if (updateTime != null) {
                        Date date = Date.from(updateTime.atZone(ZoneId.systemDefault()).toInstant());
                        object.putOpt("commentTime", sdf.format(date));
                    }
                    re.add(object);
                }
            }
            return ResultBody.success("展示成功！", re);
        } catch (Exception e) {
            return ResultBody.error("获取评论失败", null);
        }
    }
}
